package com.android.wellcherish.workclock;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.wellcherish.workclock.bean.data.GroupRecord;
import com.android.wellcherish.workclock.bean.data.RecordAdapterHeadBean;
import com.android.wellcherish.workclock.bean.db.Record;
import com.android.wellcherish.workclock.database.AppDatabase;
import com.android.wellcherish.workclock.database.DbTaskManager;
import com.android.wellcherish.workclock.util.CommonUtil;
import com.android.wellcherish.workclock.view.LineItemDecoration;
import com.android.wellcherish.workclock.view.RecordAdapter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.List;

/**
 * @date 2019/07/07
 * @author wellcherish
 * */

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private AppDatabase database;
    private DbTaskManager manager;

    private TextView tvDate;
    private RecyclerView rvTodayRecords;
    private Button btn;

    RecordAdapter recordAdapter;

    private String[] weekdays;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }

    @Override protected void onDestroy() {
        super.onDestroy();

        database = null;
        manager.cancel();
        manager = null;
    }

    private void initView() {
        tvDate = findViewById(R.id.tv_date);
        rvTodayRecords = findViewById(R.id.rv);
        btn = findViewById(R.id.btn_clock);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                workClock(v);
            }
        });
    }

    private void initData() {
        database = AppDatabase.getInstance(this);
        manager = new DbTaskManager(this, database);
        weekdays = getResources().getStringArray(R.array.weekday);
        initRecyclerView();
        setTopDate();
    }

    /**
     * 进行初始化 RecyclerView 的样式数据等操作
     * */
    private void initRecyclerView() {
        // 拿到今天的数据
        List<Record> todayRecords = manager.querySomedayRecords(Instant.now());
        List<GroupRecord> todayGroupRecords = CommonUtil.getGroupRecords(todayRecords, false);
        if(!CommonUtil.isEmptyList(todayGroupRecords)) {
            // 设置今日打卡
            ((RecordAdapterHeadBean)todayGroupRecords.get(0).getData().get(0)).setDate(getString(R.string.today_clock));
            // 拿到今天的数据，进行显示
            recordAdapter = new RecordAdapter(this, todayGroupRecords);
            recordAdapter.setCanFold(false);
            rvTodayRecords.addItemDecoration(new LineItemDecoration(CommonUtil.dpToPx(this, 1),
                CommonUtil.dpToPx(this, 40), CommonUtil.dpToPx(this, 0)));
            rvTodayRecords.setLayoutManager(new LinearLayoutManager(this));
            rvTodayRecords.setAdapter(recordAdapter);
        } else {
            Log.d(TAG, "今日数据为空，不显示数据");
        }
    }

    /**
     * 设置主页顶部的日期信息
     * */
    private void setTopDate() {
        LocalDate date = LocalDate.now();
        // 获取日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = date.format(formatter);
        // 获取星期几
        dateStr += (" " + weekdays[date.get(ChronoField.DAY_OF_WEEK) - 1]);

        tvDate.setText(dateStr);
    }

    /**
     * 点击一次按钮，记录一次打卡记录
     * */
    public void workClock(View view) {
        saveData();
        // 重新刷新布局
        List<Record> todayRecords = manager.querySomedayRecords(Instant.now());
        List<GroupRecord> groupRecords = CommonUtil.getGroupRecords(todayRecords, false);
        if(!CommonUtil.isEmptyList(groupRecords)) {
            // 设置今日打卡
            ((RecordAdapterHeadBean)groupRecords.get(0).getData().get(0)).setDate(getString(R.string.today_clock));
            if(recordAdapter != null) {
                recordAdapter.setData(groupRecords);
            }
        } else {
            Log.d(TAG, "刷新数据为空，不显示数据");
        }
    }

    /**
     * 将必要的数据永久存储，包括打卡记录和当日打卡次数
     * */
    private void saveData() {
        // 获取当前时间
        Instant instant = Instant.now();
        // 生成数据库的数据项
        Record record = new Record(instant.getEpochSecond(), instant.getNano());
        //将记录存入数据库中
        manager.insert(record);
    }

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.record, menu);
        return true;
    }

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_record:
                Intent i = new Intent(MainActivity.this, RecordsActivity.class);
                startActivity(i);
                break;
            case R.id.menu_search:
                i = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(i);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}